package org.ku.hero;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.ku.hero.codec.PacketDecoder;
import org.ku.hero.codec.PacketEncoder;
import org.ku.hero.handler.HeartBeatRespHandler;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class EvNettyServer {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(EvNettyServer.class);

    public static EvNettyServer instance(){
        return EvNettyServerFactory.SERVER;
    }

    private static class EvNettyServerFactory{
        private static final EvNettyServer SERVER = new EvNettyServer();
    }

    private static final int BIZTHREADSIZE = 100;//处理业务线程数
    private static final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
    private static String ip;
    private static int port;

    private EvNettyServer(){    }

    public void bind(String ip,int port) throws InterruptedException {
        this.ip = ip;
        this.port = port;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workerGroup)
                .option(ChannelOption.SO_BACKLOG,100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new PacketDecoder(Integer.MAX_VALUE, 4, 4));
                        pipeline.addLast(new PacketEncoder());
                        pipeline.addLast(new HeartBeatRespHandler());
                    }
            });

        ChannelFuture future = bootstrap.bind(ip,port).sync();
        logger.info(String.format("【EV数据接收服务器】 %s:%s 启动成功",ip,port));
        future.channel().closeFuture().sync();
    }

    public void shutdown(){
        if (workerGroup.isTerminated()){
            workerGroup.shutdownGracefully();
        }
        if (bossGroup.isTerminated()){
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        EvNettyServer.instance().bind("127.0.0.1",8080);
    }
}
